var router = require('express').Router();
var util = require('util');
var EventProxy = require("eventproxy");
var async = require('async');

var Consts = require('../consts');
var resultJson = require('../result-json');
var Utils = require('../utils');
var logger = require('../models/logger');
var Direction = require('../models/Direction');
var Course = require('../models/Course');
var Project = require('../models/Project');
var User = require('../models/User');

router.post('/', function(req, res) {
	res.send('respond with a resource');
});

//查询方向下的课程或项目
router.post("/listCourseOrProject", function(req, res) {
	var field = req.body.field; //课程course  项目project
	var category = req.body.category; //方向id
	var full = req.body.full; // true  false
	if (category) {
		Direction.findById(category).exec(function(err, direction) {
			if (err) {
				logger.error(err);
				return res.send(resultJson(2));
			}
			if (!direction)
				return res.send(resultJson(0));
			if (full == "true" || full == true) {
				var coursesId = [],
					projectsId = [];
				var coursesLength = (direction.courses || []).length;
				var projectsLength = (direction.pojects || []).length;
				for (var i = 0; i < coursesLength.length; i++) {
					coursesId.push(direction.courses[i].id);
				};
				for (var i = 0; i < projectsLength.length; i++) {
					projectsId.push(direction.projects[i].id);
				};
				direction = JSON.parse(JSON.stringify(direction));
				async.parallel({
					courses: function(cb) {
						Course.find({
							_id: {
								$in: coursesId
							}
						}, {

						}, function(err, courses) {
							cb(err, courses);
						});
					},
					projects: function(cb) {
						Project.find({
							_id: {
								$in: projectsId
							}
						}, {}, function(err, projects) {
							cb(err, projects);
						});
					}
				}, function(err, results) {
					if (err) {
						logger.error(err);
						return cb(err);
					}
					direction.courses = results.courses;
					direction.projects = results.projects;
					res.send(resultJson(0, direction));
				});
			} else {
				res.send(resultJson(0, direction));
			}
		});
	} else {
		if (field == "course") {
			Course.find({
				status: Consts.STATUS.PASS
			}).exec(function(err, courses) {
				if (err) {
					logger.error(err);
					return res.send(resultJson(2));
				}
				res.send(resultJson(0, courses));
			});
		} else if (field == "project") {
			Project.find({
				status: Consts.STATUS.PASS
			}).exec(function(err, projects) {
				if (err) {
					logger.error(err);
					return res.send(resultJson(2));
				}
				res.send(resultJson(0, projects));
			});
		} else
			res.send(resultJson(3));
	}
});

//查询方向下的课程
router.post("/listCourse", function(req, res) {
	var category = req.body.category; //方向id
	var full = req.body.full; // true  false
	if (category) {
		Direction.findById(category).exec(function(err, direction) {
			if (err) {
				logger.error(err);
				return res.send(resultJson(2));
			}
			if (!direction)
				return res.send(resultJson(0));
			if (full == "true" || full == true) {
				var coursesId = [];
				var coursesLength = (direction.courses || []).length;
				for (var i = 0; i < coursesLength; i++)
					coursesId.push(direction.courses[i].id);
				Course.find({
					_id: {
						$in: coursesId
					}
				}, {
					_id: 1,
					name: 1,
					create: 1,
					desc: 1,
					photo: 1,
					classHour: 1
				}, function(err, courses) {
					res.send(resultJson(0, courses));
				});
			} else
				res.send(resultJson(0, direction.courses));
		});
	} else {
		Course.find({
			status: Consts.STATUS.PASS
		}, {
			_id: 1,
			name: 1,
			create: 1,
			desc: 1,
			photo: 1,
			classHour: 1
		}).exec(function(err, courses) {
			if (err) {
				logger.error(err);
				return res.send(resultJson(2));
			}
			res.send(resultJson(0, courses));
		});
	}
});

//查询方向下的课程或项目
router.post("/listProject", function(req, res) {
	var category = req.body.category; //方向id
	var full = req.body.full; // true  false
	if (category) {
		Direction.findById(category).exec(function(err, direction) {
			if (err) {
				logger.error(err);
				return res.send(resultJson(2));
			}
			if (!direction)
				return res.send(resultJson(0));
			if (full == "true" || full == true) {
				var projectsId = [];
				console.log(direction);
				var projectsLength = (direction.projects || []).length;
				console.log(projectsLength)
				for (var i = 0; i < projectsLength; i++)
					projectsId.push(direction.projects[i].id);
				console.log("projectId:" + projectsId)
				Project.find({
					_id: {
						$in: projectsId
					}
				}, {
					_id: 1,
					name: 1,
					create: 1,
					desc: 1,
					picture: 1
				}, function(err, projects) {
					res.send(resultJson(0, projects));
				});
			} else {
				res.send(resultJson(0, direction.projects));
			}
		});
	} else {
		Project.find({
			status: Consts.STATUS.PASS
		}, {
			_id: 1,
			name: 1,
			create: 1,
			desc: 1,
			picture: 1
		}).exec(function(err, projects) {
			if (err) {
				logger.error(err);
				return res.send(resultJson(2));
			}
			res.send(resultJson(0, projects));
		});
	}
});

//查询方向
router.post('/list', function(req, res) {
	var direction = req.body;
	var proxy = new EventProxy();
	proxy.all("results", "count", function(results, count) {
		res.send(resultJson(0, {
			results: results,
			count: count
		}))
	})
	var start = direction.start || 0;
	var count = direction.count || Consts.MAX;
	Direction.find({}).skip(start).limit(count).sort({
		create: -1
	}).exec(function(err, directions) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		proxy.emit("results", directions);
	});

	Direction.find().count(function(err, num) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		proxy.emit("count", num);
	});
});

router.post('/detail', function(req, res) {
	var _id = req.body._id;
	if (!_id)
		return res.send(resultJson(3));

	Direction.findOne({
		_id: _id
	}).exec(function(err, direction) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		direction = JSON.parse(JSON.stringify(direction));
		var courseId = [],
			projectId = [];
		if (direction.courses)
			for (var i = 0; i < direction.courses.length; i++) {
				if (direction.courses[i].id)
					courseId.push(direction.courses[i].id);
			};
		if (direction.projects)
			for (var i = 0; i < direction.projects.length; i++) {
				if (direction.projects[i].id)
					projectId.push(direction.projects[i].id);
			};
		async.parallel({
			courses: function(areascb) {
				// 查询所在地区
				Course.find({
					_id: {
						$in: courseId
					}
				}, {
					_id: 1,
					name: 1
				}, function(err, area) {
					areascb(err, area);
				});
			},
			projects: function(postscb) {
				// 查询岗位
				Project.find({
					"_id": {
						$in: projectId
					}
				}, {
					_id: 1,
					name: 1
				}, function(err, posts) {
					postscb(err, posts);
				});
			}
		}, function(err, results) {
			if (err) {
				logger.error(err);
				return res.send(resultJson(2));
			}
			direction.courses = results.courses;
			direction.projects = results.projects;
			res.send(resultJson(0, direction));
		});
	});
});

//添加或修改方向
router.post('/upsert', function(req, res) {
	var direction = req.body;
	direction = JSON.stringify(direction);
	direction = direction.replace(/\</g, '&lt;').replace(/\>/g, '&gt;').replace(/</g, '&lt;').replace(/>/g, '&lg;');
	direction = JSON.parse(direction);
	if (!direction.name || !direction.desc)
		return res.send(resultJson(3));
	if (direction._id) { //update
		if (!direction.courses)
			direction.courses = [];
		if (!direction.projects)
			direction.projects = [];
		//名字唯一性判断
		Direction.count({
			name: direction.name,
			_id: {
				$ne: direction._id
			}
		}, function(err, cnt) {
			if (err)
				return res.send(resultJson(2));
			if (cnt)
				return res.send(resultJson(401));
			Direction.update({
				_id: direction._id
			}, {
				$set: direction
			}).exec(function(err) {
				if (err) {
					logger.error(err);
					return res.send(resultJson(2));
				}
				res.send(resultJson(0));
			});
		});
	} else { //add
		//名字唯一性判断
		Direction.count({
			name: direction.name
		}, function(err, cnt) {
			if (err)
				return res.send(resultJson(2));
			if (cnt)
				return res.send(resultJson(401));

			direction.create = new Date();
			new Direction(direction).save(function(err, direction) {
				if (err) {
					logger.error(err);
					return res.send(resultJson(2));
				}
				res.send(resultJson(0, direction));
			});
		});
	}
});

//删除方向
router.post('/remove', function(req, res) {
	var direction = req.body;
	Direction.remove({
		_id: direction._id
	}, function(err) {
		if (err) {
			logger.error(err);
			res.send(resultJson(2));
		} else
			res.send(resultJson(0));
	})
});
module.exports = router;